package com.dycong.common.IO.netty.ssl.client;

import com.dycong.common.IO.netty.ssl.KeyStoreAndTrustConfig;
import io.netty.util.internal.SystemPropertyUtil;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;

/**
 * Created by dycong on 2017/4/5.
 */
public final class SecureSocketSslContextFactory {
    private static final String PROTOCOL = "TLS";
    private static SSLContext SERVER_CONTEXT = null;
    private static SSLContext CLIENT_CONTEXT = null;

    static {
        String algorithm = SystemPropertyUtil.get("ssl.KeyManagerFactory.algorithm");
        if (algorithm == null) {
            algorithm = "SunX509";
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(KeyStoreAndTrustConfig.getServerKeystoreFilepath()), KeyStoreAndTrustConfig.getServerKeyFilePw().toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
            kmf.init(keyStore, KeyStoreAndTrustConfig.getServerKeyPw().toCharArray());

            KeyStore tKeyStore = KeyStore.getInstance("JKS");
            tKeyStore.load(new FileInputStream(KeyStoreAndTrustConfig.getServerTrustFilepath()), KeyStoreAndTrustConfig.getServerTrustFilePw().toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
            tmf.init(tKeyStore);

            SERVER_CONTEXT = SSLContext.getInstance(PROTOCOL);
            SERVER_CONTEXT.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());


            KeyStore clientKeyStore = KeyStore.getInstance("JKS");
            clientKeyStore.load(new FileInputStream(KeyStoreAndTrustConfig.getClientKeystoreFilepath()), KeyStoreAndTrustConfig.getClientKeyFilePw().toCharArray());
            KeyManagerFactory clientKMF = KeyManagerFactory.getInstance(algorithm);
            clientKMF.init(clientKeyStore, KeyStoreAndTrustConfig.CLIENT_KEY_PW.toCharArray());

            KeyStore clientTrust = KeyStore.getInstance("JKS");
            clientTrust.load(new FileInputStream(KeyStoreAndTrustConfig.getClientTrustFilepath()), KeyStoreAndTrustConfig.getClientTrustFilePw().toCharArray());
            TrustManagerFactory clientTMF = TrustManagerFactory.getInstance(algorithm);
            clientTMF.init(clientTrust);

            CLIENT_CONTEXT = SSLContext.getInstance("SSL");
            CLIENT_CONTEXT.init(clientKMF.getKeyManagers(), clientTMF.getTrustManagers(), new SecureRandom());

        } catch (Exception e) {

        }
    }

    public static String getPROTOCOL() {
        return PROTOCOL;
    }

    public static SSLContext getServerContext() {
        return SERVER_CONTEXT;
    }

    public static SSLContext getClientContext() {
        return CLIENT_CONTEXT;
    }
}
